﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WPFTools {
    static public class Logger
    {
        static public string logFile = $"{Directory.GetCurrentDirectory()}/Log/Log_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.txt";
        // 输出同时写日志
        static public void WriteLog(string str)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(logFile));
            File.AppendAllText(logFile, str);
            Console.Write(str);
        }
        static public void AppendText(this RichTextBox rtb, string str, Color color, bool isNewParagraph, ushort fontSize) {
            var newRun = new Run(str);
            newRun.FontFamily = rtb.FontFamily;
            newRun.FontSize = fontSize;
            newRun.Foreground = new SolidColorBrush(color);
            if (isNewParagraph) {
                rtb.Document.Blocks.Add(new Paragraph(newRun));
                var newRun2 = new Run("");
                rtb.Document.Blocks.Add(new Paragraph(newRun2));
            }
            else {
                var para = rtb.Document.Blocks.LastBlock as Paragraph;
                if (para == null) {
                    MessageBox.Show("获取到的Block不为ParaGraph，该异常未处理！");
                    throw new Exception("获取到的Block不为ParaGraph，该异常未处理！");
                }
                para.Inlines.Add(newRun);
            }
        }
        // 
        static public void WriteLog(string str, RichTextBox rtb, Color color, bool newParagraph = false, ushort fontSize = 14) {
            rtb.AppendText(str, color, newParagraph, fontSize);
            WriteLog(str);
        }
        static public void WriteLog(string str, RichTextBox rtb, bool newParagraph = true, ushort fontSize = 14) {
            var color = new Color();
            if (rtb.Foreground is SolidColorBrush solidColorBrush) {
                color = solidColorBrush.Color;
            }
            else {
                WriteLog("从空间获取的 Foreground 类型并非 SolidColorBrush，请解决该错误！\n", rtb, Colors.Red);
                throw new Exception("从空间获取的 Foreground 类型并非 SolidColorBrush，请解决该错误！\n");
            }
            WriteLog(str, rtb, color, newParagraph, fontSize);
        }
    }
}
